package com.example.demo.thread.loopPrint;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 该思路和synchronized+wait/notify方法的很像，
 * synchronized对应lock，
 * await/signal方法对应wait/notify方法。
 * 下面的代码为了能精准地唤醒下一个线程，创建了多个Condition对象。
 */
public class LockConditionABC {
    private Integer num = 0;
    private static Lock lock = new ReentrantLock();

    private static Condition conditionA = lock.newCondition();
    private static Condition conditionB = lock.newCondition();
    private static Condition conditionC = lock.newCondition();

    private void printABC(int targetNum,Condition currentThead,Condition nextThread){
        for(int i = 0; i < 50;){
            lock.lock();
            try {
                while(num % 3 != targetNum){
                    currentThead.await();
                }
                System.out.println(Thread.currentThread().getName() + ":" + num);
                num++;
                i++;
                nextThread.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        LockConditionABC print = new LockConditionABC();
        new Thread(() -> print.printABC(0,conditionA,conditionB), "A").start();
        new Thread(() -> print.printABC(1,conditionB,conditionC), "B").start();
        new Thread(() -> print.printABC(2,conditionC,conditionA), "C").start();

    }
}
